//
//  Extension+UIApplication.swift
//  TCMHealth
//
//  Created by 韩颖 on 2023/7/2.
//

import Foundation
import UIKit

/**确保在主线程执行,但是当前如果是主线程就减少不必要的线程切换的开支**/
func MainThread(_ block:@escaping ()->()){
    if Thread.current.isMainThread {
        block()
    } else {
        DispatchQueue.main.async {
            block()
        }
    }
}

/**
 当前最顶层的控制器
 */
var k_currentVC : UIViewController {
    get {
        if let rootVC = k_currentWindow?.rootViewController {
            return UIViewController.k_currentViewController(from: rootVC)
        } else {
            return UIViewController()
        }
    }
}

/**
 当前显示的 window
 */
var k_currentWindow : UIWindow? {
    get{
//        if #available(iOS 14.0, *) {
//
//            let windows = UIApplication.shared.connectedScenes.map({$0 as? UIWindowScene}).compactMap({$0})
//
//         if let window = UIApplication.shared.connectedScenes.map({$0 as? UIWindowScene}).compactMap({$0})
//
//          .first?.windows.first {
//
//          return window
//
//         }else if let window = UIApplication.shared.delegate?.window {
//
//          return window
//
//         }else{
//
//          return nil
//
//         }
//
//        } else
        
        
        
        if #available(iOS 13.0, *) {

         if let window = UIApplication.shared.connectedScenes

          .filter({$0.activationState == .foregroundActive})

          .map({$0 as? UIWindowScene})

          .compactMap({$0})

          .first?.windows

          .filter({$0.isKeyWindow}).first{

          return window

         }else if let window = UIApplication.shared.delegate?.window {

          return window

         }else{

          return nil

         }

        }else{

         if let window = UIApplication.shared.delegate?.window {

          return window

         }else{

          return nil

         }

        }
    }
}

/**
 当前安全区域的底部高度
 */
var k_safeAreaInsets_Bottom : CGFloat {
    get{
        guard let window = k_currentWindow else {return 0}
        return window.safeAreaInsets.bottom
    }
}

// MARK: 屏幕尺寸
let kScreenWidth = UIScreen.main.bounds.size.width
let kScreenHeight = UIScreen.main.bounds.size.height
let stateHeight = UIApplication.shared.statusBarFrame.height
/// 底部导航栏高度
let k_tabBarHeight = 49.0
/// 底部导航栏高度（包括安全区）
let k_tabBarFullHeight = k_tabBarHeight + k_safeAreaInsets_Bottom
// MARK: 分类方法
extension UIApplication {
    func exitApp(){
        perform(#selector(NSXPCConnection.suspend))
    }

}
